/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.middleware.quartz.job.djtax;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.TjReportService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.Calendar;
import java.util.stream.Collectors;

/**
 * 东疆税务上报脚本
 *
 * @author duanlikao
 * @created 2021/5/13
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class DjTaxUploadJobService implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(DjTaxUploadJobService.class);

    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Autowired
    private IHyCompanyService hyCompanyService;

    @Autowired
    private IHyCustomerService hyCustomerService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyVehicleService hyVehicleService;


    @Autowired
    private IHyCompanyConfigService companyConfigService;

    @Autowired private TjReportService tjReportService;


    //@Scheduled(cron = "0 01 1 * * ?")//每天的01:01:00执行 临时注释
//    @Scheduled(cron = "0 30 08 1 * ?")//每月1号的01:10:00执行
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getDongjiangIzUse()){
            LOGGER.info("天津东疆税务上报服务暂未开启,请联系管理员。" );
            return;
        }

        List<HyCompanyConfig> companyConfigs = companyConfigService.list(new QueryWrapper<HyCompanyConfig>()
                .eq("tax_upload_type", 1)
               // .eq("tj_tax_upload_status","1")
        );
        if(CollectionUtils.isEmpty(companyConfigs)) {
            LOGGER.info("UploadJobService autoUploadShippingNote: 没有分公司配置税务上报 !" );
            return;
        }
        Long start = System.currentTimeMillis();
        LOGGER.info("UploadJobService autoUploadShippingNote:执行税务上报运单数据开始" + DateUtils.getDateStr());

        for (HyCompanyConfig companyConfig : companyConfigs) {

            QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper();
            queryWrapper.eq("shipping_pay_status","6");
            queryWrapper.eq("order_mode","1");//管理费模式
            queryWrapper.eq("tax_upload_flag","0"); //税务上报标识(0正常 1取消上报)
            queryWrapper.ne("tax_upload_status","1");
            //天津分公司
            queryWrapper.eq("company_id",companyConfig.getCompanyId());



            Date now1 = new Date();
            int month =   now1.getMonth()+1 ;
            if(month == 1){
                java.util.Calendar calendar = new GregorianCalendar();
                calendar.setTime(now1);
                calendar.add(java.util.Calendar.MONTH, -1);// 把日期往后增加一天.整数往后推,负数往前移动
                // 获取某月最小天数
                int firstDay = calendar.getActualMinimum(java.util.Calendar.DAY_OF_MONTH);
                // 设置日历中月份的最小天数
                calendar.set(Calendar.DAY_OF_MONTH, firstDay);

                Date endDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
                String yearStartTime = DateUtils.date2Str(endDate , DateUtils.date_sdf.get()) + " 00:00:00";
                queryWrapper.ge("pay_dt",yearStartTime);
            }else{
                String  yearStartTime =  DateUtils.formatDate1(DateUtils.getYearStartTime(start));
                queryWrapper.ge("pay_dt",yearStartTime);
            }


            queryWrapper.orderByDesc("pay_dt");
            List<HyShippingNote> shippingNoteNumbers  = new ArrayList <>();
            List<HyShippingNote> shippingNotes =  shippingNoteService.list(queryWrapper);
            if(CollectionUtils.isEmpty(shippingNotes)) {
                LOGGER.info("UploadJobService autoUploadShippingNote: no data handling !" );
                continue;
            }
            for(HyShippingNote hyShippingNote:shippingNotes){
                try {
                    tjReportService.uploadTax(hyShippingNote);
                    uploadDriver(hyShippingNote.getDriverId(),hyShippingNote.getVehicleId());
                    uploadCompany(hyShippingNote.getCompanyId());
                    uploadCustomer(hyShippingNote.getCustomerId());
                }catch (Exception e){
                    LOGGER.info("UploadJobService autoUploadShippingNote:Exception : {}" ,e.getMessage());
                    continue;
                }
            }
            if(CollectionUtils.isNotEmpty(shippingNoteNumbers)){
                for(HyShippingNote ShippingNoteDb : shippingNoteNumbers){
                    ShippingNoteDb.setTaxUploadStatus("2");
                    ShippingNoteDb.setTaxUploadDate(new Date());
                    ShippingNoteDb.setTaxFailureReason("运单收发货时间小于一小时,需人工审核推送");
                }
                shippingNoteService.updateBatchById(shippingNoteNumbers);
                List<String> shippingNoteNumber = shippingNoteNumbers.stream().map(item->item.getShippingNoteNumber()).collect(Collectors.toList());

                LOGGER.info("UploadJobService autoUploadShippingNote: Less than an hour 总数:{},  运单: {} " ,shippingNoteNumber.size() ,shippingNoteNumber);

            }

        }


      LOGGER.info("UploadJobService autoUploadShippingNote:执行税务上报运单数据结束,耗时:"+(System.currentTimeMillis()-start)+"毫秒----");

    }

    private void  uploadDriver(String driverId,String vehicleId){
        HyVehicle hyVehicle = hyVehicleService.getById(vehicleId);
        hyDriverService.tjTaxUpload(hyDriverService.getById(driverId),hyVehicle);
    }

    private void  uploadCompany(String companyId){
            hyCompanyService.tjTaxUpload(companyId);
    }

    private void  uploadCustomer(String customerId){
        HyCustomer hyCustomer = hyCustomerService.getById(customerId);
        if(hyCustomer != null && !"1".equals(hyCustomer.getTjTaxUploadStatus()) ) {
            hyCustomerService.tjTaxUpload(hyCustomer);
        }
    }




}
